/*
 * @Author: actor
 * @Date: 2023-11-13 15:43:57
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-19 10:12:53
 * @FilePath: \i-hos-app\shared\emr\src\hooks\useInsertComponent.ts
 * @Description: 组件插入
 */
import { toRefs } from 'vue'
// 接口约束
import { IPageConfigStore } from '../interface/page'
// store数据
import { usePageConfigStore } from '../store/pageConfig'
// 公共方法
import { generateMixed } from '../utils/index'
// 获取公共的hooks
import { useCommon } from '../hooks/useCommon'
import { useHandleTable } from '../hooks/useHandleTable'

// 插入对应选择的组件
export const useInsertComponent = (node: HTMLElement, type?: string, defaultVal?: any): void => {
  // 获取设置属性
  const { handleHtml, findParents } = useCommon()
  let { initTdRc } = useHandleTable()

  // 解构 store的配置数据, 获取光标的位置或选定对象
  const pageConfigStore: IPageConfigStore = usePageConfigStore()
  const { lastAangeAt } = toRefs<any>(pageConfigStore)
  let rangeAt: any = lastAangeAt.value

  // 如果有光标对象， 判断是不是再编辑的区域内
  if (rangeAt != null) {
    let rangeNode = findParents(rangeAt.commonAncestorContainer, { cls: 'emr_page_editArea' }, true)
    if (rangeNode.length == 0) return
  }

  // 判断是否存在光标的位置或选定对象，如果没有就在电子病历
  if (rangeAt == null) {
    let element: any = document.querySelector('#emr_page_body')?.querySelector('.emr_page_editArea')
    let selection: any = window.getSelection && window.getSelection()
    let range = document.createRange()
    range.selectNodeContents(element)
    selection.removeAllRanges()
    selection.addRange(range)
    rangeAt = selection.getRangeAt(0)
  }

  // 设置元素的id
  let firstchild = node.firstElementChild as any
  if (!!firstchild.dataset.config) {
    let config = JSON.parse(firstchild.dataset.config)
    if (config.name != undefined) {
      firstchild.id = generateMixed()
    }
    // 插入的表格元素进行初始化处理
    if (firstchild.tagName == 'TABLE') {
      initTdRc(firstchild)
    }
  }

  // 插入的元素
  let innerHtml: any = rangeAt.createContextualFragment(
    (node.innerHTML as string) + (firstchild.tagName != 'TABLE' ? '&nbsp' : '')
  )
  // 记录插入的最后节点位置
  let lastNode: string = innerHtml.lastChild
  // 插入元素
  rangeAt.insertNode(innerHtml)

  // 针对需要处理的元素进行处理
  handleHtml(document.querySelector('#emr_page')?.querySelectorAll('.selectBoxForm'), type)

  // 添加了新内容，将光标移动到新的位置
  if (lastNode) {
    rangeAt.setStartAfter(lastNode)
  }
  // 光标开始和光标结束重叠
  rangeAt.collapse(true)
  // 清除选定对象的所有光标对象
  selection?.removeAllRanges()
  // 插入新的光标对象
  selection?.addRange(rangeAt)
  // 记录最后光标对象
  var selection: any = window.getSelection && window.getSelection()
  // 修改配置仓库
  pageConfigStore.$patch?.((state: IPageConfigStore) => {
    // 设置电子侧栏选中状态
    state.asideTabsActive = 'attr'
    // 记录最后光标位置
    state.lastAangeAt = rangeAt
    //设置配置的元素
    let config: any
    if (!!defaultVal) {
      let _cif = JSON.parse(firstchild.dataset.config),
        _targetNode = document.getElementById(`${firstchild.id}`) as any,
        _createSpan: HTMLElement = document.createElement('span')
      // 设置配置
      _cif.des = defaultVal.des
      _cif.code = defaultVal.code
      if (defaultVal.option.length > 0) {
        _cif.textVal = defaultVal.option[0]
        _cif.option = defaultVal.option
      }
      config = _cif
      // 当前节点处相关内容
      _createSpan.innerHTML = defaultVal.des
      _targetNode.parentNode.insertBefore(_createSpan, _targetNode)
      _targetNode.innerText = defaultVal.option.length > 0 ? defaultVal.option[0] : '文本输入域'
      _targetNode.setAttribute('data-config', JSON.stringify(_cif))
    } else {
      if (firstchild.dataset.config != undefined) {
        config = JSON.parse(firstchild.dataset.config)
      }
    }
    if (config != undefined) {
      if (config.name != undefined) {
        // config.name = ''
        state.el = firstchild.id
      }
      if (!!config.option && !!Array.isArray(config.option)) {
        config.option = config.option.join(',').replace(/,/g, '\n')
      }
      state.commonComponentActive = ''
      state.val = config
    } else {
      state.val = {}
    }
  })
}
